<template>
  <div class="shopping-container">
    <el-card class="filter-card">
      <el-form :inline="true" class="filter-form">
        <el-form-item label="商品名称">
          <el-input v-model="searchQuery" placeholder="请输入商品名称" clearable @change="handleSearch" />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="categoryFilter" placeholder="请选择分类" clearable @change="handleSearch" style="width: 100%;">
            <el-option value="" label="请选择" />
            <el-option
              v-for="category in categories"
              :key="category.categoryId"
              :label="category.name"
              :value="category.categoryId"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <div class="button-group" style="margin-bottom: 16px;">
        <el-button type="primary" @click="showCart">查看购物车</el-button>
        <el-button type="info" @click="showOrders">查看订单</el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="filteredGoodsList"
        border
        style="width: 100%"
      >
        <el-table-column prop="productId" label="商品ID" width="80" />
        <el-table-column prop="name" label="商品名称" min-width="150" />
        <el-table-column prop="description" label="商品描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="price" label="价格" width="100">
          <template #default="{ row }">
            ¥{{ row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stockQuantity" label="库存" width="100" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              @click="handleAddCart(row)"
              :disabled="row.stockQuantity === 0 || isInCart(row.productId) || isAdding[row.productId]"
            >
              {{ isInCart(row.productId) ? '已加入购物车' : isAdding[row.productId] ? '加入中...' : '加入购物车' }}
            </el-button>
            <el-button
              type="success"
              @click="handleDirectOrder(row)"
              :disabled="row.stockQuantity === 0"
            >
              直接下单
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog v-model="cartVisible" title="购物车" width="50%">
      <el-table :data="cartItems" border>
        <el-table-column prop="productId" label="商品ID" width="80" />
        <el-table-column prop="name" label="商品名称" min-width="150" />
        <el-table-column prop="quantity" label="数量" width="150">
          <template #default="{ row }">
            <el-input-number
              v-model="row.quantity"
              :min="1"
              :max="row.stockQuantity"
              size="small"
              @change="updateCart(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价" width="100">
          <template #default="{ row }">
            ¥{{ row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="总价" width="100">
          <template #default="{ row }">
            ¥{{ (row.price * row.quantity).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button type="danger" @click="removeFromCart(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="cart-footer">
        <p>总计：¥{{ totalPrice }}</p>
        <el-button type="danger" @click="clearCart">清空购物车</el-button>
        <el-button type="success" @click="checkoutCart">结算</el-button>
      </div>
    </el-dialog>

    <el-dialog v-model="ordersVisible" title="我的订单" width="60%">
      <el-table :data="orderList" border>
        <el-table-column prop="order.orderId" label="订单ID" width="80" />
        <el-table-column label="商品信息" min-width="200">
          <template #default="{ row }">
            <div v-for="item in row.orderItems" :key="item.orderItemId">
              {{ item.productId }} - 数量: {{ item.quantity }} - 单价: ¥{{ item.unitPrice.toFixed(2) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="order.totalAmount" label="总金额" width="120">
          <template #default="{ row }">
            ¥{{ row.order.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="order.status" label="状态" width="100" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <div class="button-group">
              <el-button
                v-if="row.order.status === 'pending'"
                type="primary"
                size="small"
                @click="handlePayment(row)"
              >
                支付
              </el-button>
              <el-button
                v-if="row.order.status === 'pending'"
                type="danger"
                size="small"
                @click="handleCancelOrder(row)"
              >
                取消订单
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="order.createdAt" label="创建时间" width="160" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getProducts,
  getProductCategories,
  getProductsByCategoryId,
  addToCartApi,
  getCartContent,
  updateCartQuantity,
  deleteFromCart,
  createOrderFromCart,
  createOrderDirect,
  clearCartApi,
  getUserOrders,
  createPayment,
  cancelOrder
} from '@/api/api'

const searchQuery = ref('')
const categoryFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const goodsList = ref([])
const categories = ref([])
const cartItems = ref([])
const cartVisible = ref(false)
const ordersVisible = ref(false)
const orderList = ref([])
const loading = ref(false)
const isAdding = ref({})

const filteredGoodsList = computed(() => {
  let filtered = goodsList.value.filter(item => {
    const matchesName = item.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    return matchesName
  })
  total.value = filtered.length
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

const totalPrice = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + item.price * item.quantity, 0).toFixed(2)
})

const fetchProducts = async () => {
  try {
    loading.value = true
    let res
    if (categoryFilter.value) {
      res = await getProductsByCategoryId(categoryFilter.value)
    } else {
      res = await getProducts()
    }
    if (res.code === 200 && res.data) {
      goodsList.value = res.data
      total.value = res.data.length
    }
  } catch (error) {
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

const fetchCategories = async () => {
  try {
    const res = await getProductCategories()
    if (res.code === 200 && res.data) {
      categories.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取商品分类失败')
  }
}

const fetchCartContent = async () => {
  try {
    const res = await getCartContent()
    if (res.code === 200 && res.data && res.data.items) {
      cartItems.value = res.data.items.map(item => {
        const product = goodsList.value.find(p => p.productId === item.productId)
        return {
          ...item,
          name: product?.name,
          price: product?.price,
          stockQuantity: product?.stockQuantity
        }
      })
    }
  } catch (error) {
    ElMessage.error('获取购物车内容失败')
  }
}

const fetchOrders = async () => {
  try {
    const res = await getUserOrders()
    if (res.code === 200 && res.data) {
      orderList.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取订单列表失败')
  }
}

const isInCart = (productId) => {
  return cartItems.value.some(item => item.productId === productId)
}

const handleSearch = async () => {
  currentPage.value = 1
  await fetchProducts()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const handleAddCart = async (item) => {
  if (isInCart(item.productId)) return
  try {
    isAdding.value[item.productId] = true
    await addToCartApi(item.productId, 1)
    ElMessage.success('添加成功')
    await fetchCartContent()
  } catch (error) {
    ElMessage.error('添加失败')
  } finally {
    isAdding.value[item.productId] = false
  }
}

const handleDirectOrder = async (item) => {
  try {
    const orderItems = [{
      productId: item.productId,
      quantity: 1,
      unitPrice: item.price
    }]
    const res = await createOrderDirect(orderItems)
    if (res.code === 200) {
      ElMessage.success('下单成功')
      await fetchOrders()
      await fetchProducts()
      ordersVisible.value = true
    }
  } catch (error) {
    ElMessage.error('下单失败')
  }
}

const showCart = async () => {
  await fetchCartContent()
  cartVisible.value = true
}

const showOrders = async () => {
  await fetchOrders()
  ordersVisible.value = true
}

const updateCart = async (item) => {
  try {
    await updateCartQuantity(item.productId, item.quantity)
    ElMessage.success('更新成功')
    await fetchCartContent()
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

const removeFromCart = async (item) => {
  try {
    await deleteFromCart(item.productId)
    ElMessage.success('移除成功')
    await fetchCartContent()
  } catch (error) {
    ElMessage.error('移除失败')
  }
}

const clearCart = async () => {
  try {
    await clearCartApi()
    ElMessage.success('购物车已清空')
    cartItems.value = []
    await fetchCartContent()
  } catch (error) {
    ElMessage.error('清空购物车失败')
  }
}

const checkoutCart = async () => {
  try {
    const cartId = JSON.parse(localStorage.getItem('cartId'))
    const items = cartItems.value.map(item => ({
      productId: item.productId,
      quantity: item.quantity,
      unitPrice: item.price
    }))
    const res = await createOrderFromCart(cartId, items)
    if (res.code === 200) {
      await clearCartApi()
      ElMessage.success('结算成功')
      cartItems.value = []
      cartVisible.value = false
      await fetchProducts()
      await fetchOrders()
    }
  } catch (error) {
    ElMessage.error('结算失败')
  }
}

const handlePayment = async (order) => {
  try {
    const res = await createPayment(order.order.orderId, order.order.totalAmount)
    if (res.code === 200) {
      ElMessage.success('支付成功')
      await fetchOrders()
    }
  } catch (error) {
    ElMessage.error('支付失败')
  }
}

const handleCancelOrder = async (order) => {
  try {
    const res = await cancelOrder(order.order.orderId)
    if (res.code === 200) {
      ElMessage.success('订单取消成功')
      await Promise.all([
        fetchOrders(),    // 刷新订单列表
        fetchProducts()   // 刷新商品列表
      ])
    } else {
      ElMessage.error(res.message || '取消订单失败')
    }
  } catch (error) {
    console.error('取消订单失败:', error)
    ElMessage.error('取消订单失败')
  }
}

onMounted(() => {
  fetchProducts()
  fetchCategories()
})
</script>

<style scoped>
.shopping-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.cart-footer {
  text-align: right;
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
}

.button-group {
  display: flex;
  gap: 8px;
}

.filter-form .el-form-item__content {
  width: 100%;
}
</style>